var FormValidator_V;
var FormValidator_V_Cleari=0;
function validator(){
	 FormValidator_V=new LongTimeFormValidator();
	 return FormValidator_V;
}
LongTimeFormValidator = function(){	
	this.Require = /.+/;
	this.Email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	this.Phone = /^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/;
	this.Mobile = /^((\(\d{3}\))|(\d{3}\-))?13\d{9}$/;
	this.Url = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
	this.IdCard = /^\d{15}(\d{2}[A-Za-z0-9])?$/;
	this.Currency = /^\d+(\.\d+)?$/;
	//Number = /^\d+$/;
	this.NumberRex = /^\d+$/;
	this.Number = "this.numberL(value,o.getAttribute('length'))&&this.numberMinMax(value,o.getAttribute('min'),o.getAttribute('max'))";
	this.Zip = /^[1-9]\d{5}$/;
	this.QQ = /^[1-9]\d{4,8}$/;
	//Integer = /^[-\+]?\d+$/;
	this.IntegerRex = /^[-\+]?\d*$/;
	this.Int = "this.integerL(value,o.getAttribute('length'))&&this.numberMinMax(value,o.getAttribute('min'),o.getAttribute('max'))";
	this.Integer = "this.integerL(value,o.getAttribute('length'))&&this.numberMinMax(value,o.getAttribute('min'),o.getAttribute('max'))";
	//Double = /^[-\+]?\d+(\.\d+)?$/;
	this.DoubleRex = /^[-\+]?\d*(\.\d*)?$/;
	this.Double = "this.doubleP(value,o.getAttribute('length'),o.getAttribute('precision'))&&this.numberMinMax(value,o.getAttribute('min'),o.getAttribute('max'))";
	this.English = /^[A-Za-z]+[0-9]*$/;
	this.Chinese = /^[\u0391-\uFFE5]+$/;
	this.UnSafe = /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/;
	this.IsSafe = function(str){return !this.UnSafe.test(str);};
	this.SafeString = "this.IsSafe(value)";
	this.String= "this.limit(this.LenB(value), o.getAttribute('min'), o.getAttribute('max'))";
	this.Limit = "this.limit(value.length,o.getAttribute('min'), o.getAttribute('max'))";
	this.LimitB = "this.limit(this.LenB(value), o.getAttribute('min'), o.getAttribute('max'))";
	this.Date = "this.IsDate(value,o.getAttribute('format'))";
	this.DateTime = "this.IsDateTime(value,o.getAttribute('format'))";
	this.Repeat = "value == document.getElementsByName(o.getAttribute('to'))[0].value";
	this.Range = "o.getAttribute('min') < value && value < o.getAttribute('max')";
	this.Compare = "this.compare(value,o.getAttribute('operator'),o.getAttribute('to'))";
	this.Custom = "this.Exec(value, o.getAttribute('regexp'))";
	this.Group = "this.MustChecked(o.getAttribute('name'), o.getAttribute('min'), o.getAttribute('max'))";
	this.Max="o.getAttribute('min') < value && value < o.getAttribute('max')";
	this.ErrorItem = [document.forms[0]];
	this.ErrorMessage = ["以下原因导致提交失败：\t\t\t\t"];	
	this.ElementIndex=0;	
	this.theForm=document.forms[0];
	this.mode=1;
	this.obj=1;
	this.count=0;
	this.first=true;
	this.viewstep=1;
	
}
LongTimeFormValidator.prototype.validateIt =function(){		
		while(this.ElementIndex<this.count){
			per=parseInt((this.ElementIndex+1)*100.0/this.count);			
			document.getElementById("LongTimeFormValidator_loading").style.width = per + "%";	
			document.getElementById("LongTimeFormValidator_loading").innerHTML = per + "%";	
			var o=this.obj.elements[this.ElementIndex];
			//with(this.obj.elements[this.ElementIndex])
			{				
				var _dataType = o.getAttribute("dataType");
				var _require = o.getAttribute("require");
				var value=o.value;
				if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") {
					
				}else{							
					//this.ClearState(this.obj.elements[this.ElementIndex]);					
					if(_require== "true"&&!this['Require'].test(value)){						
						this.AddError(this.ElementIndex, "必填项");//+o.getAttribute("msg")
					}
					else{
						switch(_dataType){				
						    case "DateTime" :
							case "Date" :
							case "Repeat" :
							case "Range" :
							case "Compare" :
							case "Custom" :
							case "Group" : 
							case "Limit" :
							case "String" :
							case "LimitB" :
							case "SafeString" :
							case "Int":
							case "Integer":
							case "Number":
							case "Double":
								
								if(!eval(this[_dataType])) {
									inputErrorMsg=o.getAttribute("msg");									
									if(typeof inputErrorMsg!="string"){
										if(_dataType=="Date")
											inputErrorMsg="日期不正确,应为年-月-日,如:1970-01-20";
										else if(_dataType=="Limit")
											inputErrorMsg="必须在"+o.getAttribute("max")+"个字之内";
										else if(_dataType=="LimitB")
											inputErrorMsg="必须在"+o.getAttribute("max")+"个字节之内";
										else if(_dataType=="Integer"){
											inputErrorMsg="必须为整数";
											if(typeof o.getAttribute("length")=="string")
												inputErrorMsg+=",且最多"+o.getAttribute("length")+"位";
											if(typeof o.getAttribute("max")=="string")
												inputErrorMsg+=",并且不能大于"+o.getAttribute("max");
											if(typeof o.getAttribute("min")=="string")
												inputErrorMsg+=",也不能小于"+o.getAttribute("min");
										}
										else if(_dataType=="Number"){
											inputErrorMsg="必须为数字";
											if(typeof o.getAttribute("max")=="string")
												inputErrorMsg+=",并且不能大于"+o.getAttribute("max");
											if(typeof o.getAttribute("min")=="string")
												inputErrorMsg+=",也不能小于"+o.getAttribute("min");
										}
										else if(_dataType=="Double"){
											inputErrorMsg="必须为数字,且最多";
											if(typeof o.getAttribute("precision")=="string")
												inputErrorMsg+=",且最多"+o.getAttribute("precision")+"位小数";
											if(typeof o.getAttribute("max")=="string")
												inputErrorMsg+=",并且不能大于"+o.getAttribute("max");
											if(typeof o.getAttribute("min")=="string")
												inputErrorMsg+=",也不能小于"+o.getAttribute("min");
										}
										else
											inputErrorMsg="格式不正确";
									}
									this.AddError(this.ElementIndex, inputErrorMsg);
								}
								break;
							default :
								if(!this[_dataType].test(value)){
									inputErrorMsg=o.getAttribute("msg");
									if(typeof inputErrorMsg!="string")
										inputErrorMsg=defaultMsg;
									this.AddError(this.ElementIndex, inputErrorMsg);
								}
								break;
						}						
					}
				}
					
			}
			this.ElementIndex++;
			if((this.ElementIndex-1)%this.viewstep==0&&this.ElementIndex<this.count-1){
				setTimeout("FormValidator_Validate()",1);				
				break;
			}			
			if(this.ElementIndex>=this.count){
				if(this.ErrorMessage.length > 1){
					this.mode = this.mode || 1;
					var errCount = this.ErrorItem.length;
					switch(this.mode){
						case 2 :
							for(var i=1;i<errCount;i++)
								this.ErrorItem[i].style.color = "red";
						case 1 :
							alert(this.ErrorMessage.join("\n"));
							this.ErrorItem[1].focus();
							break;
						case 3 :
							for(var i=1;i<errCount;i++){
								try{
									var span = document.createElement("SPAN");
									span.id = "__ErrorMessagePanel";
									span.name = "__ErrorMessagePanel";
									span.style.color = "red";
									this.ErrorItem[i].parentNode.appendChild(span);
									span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*");
								}
								catch(e){
									alert(e.description);
								}
							}
							this.ErrorItem[1].focus();
							break;
						default :
							alert(this.ErrorMessage.join("\n"));
							break;
					}
					document.body.removeChild(document.getElementById("LongTimeFormValidator_loaddiv"));	
					document.body.removeChild(document.getElementById("LongTimeFormValidatorBg"));	
					var s=document.getElementsByTagName("select"); 
					for(var j=0;j<s.length;j++){s[j].style.visibility="visible";} 		
						
				}	
				//document.body.removeChild(document.getElementById("LongTimeFormValidator_loaddiv"));
				//document.body.removeChild(document.getElementById("LongTimeFormValidatorBg"));	
				document.getElementById("LongTimeFormValidator_title").innerHTML ="\u6B63\u5728\u4FDD\u5B58\u6570\u636E";
				document.getElementById("LongTimeFormValidator_loading").innerHTML="<img class='img16' src='"+contextPath+"/webresource/images/loading.gif'>";
								
				this.theForm.submit();		
			}
							
		}	
	}
//增加的实数校验，需要指定长度和小数位
LongTimeFormValidator.prototype.doubleP = function(value,len,precision){
		if(typeof precision!='number')
			precision=2;
		if(typeof len!='number')
			len=9;		
		if(value.indexOf("-")==0||value.indexOf("+")==0)  len=len+1;		
		if(this.DoubleRex.test(value)){
			dot=value.indexOf(".")		
			if(dot>-1){
				i=value.substring(0,dot);			
				p=value.substring(dot+1);
				return i.length<=len-precision&&p.length<=precision;
			}else{
				return value.length<=len-precision;
			}
		}
		return false;
	}
//增加的数字型，可以通过length指定长度
LongTimeFormValidator.prototype.numberL= function(value,len){
		if(typeof len!='number')
			len=11;
		if(this.NumberRex.test(value))
			return value.length<len;
		return false;
	}
//增加的整数型，可以通过length指定长度
LongTimeFormValidator.prototype.integerL =function(value,len){	
		if(typeof len!='number')
			len=11;
		if(value.indexOf("-")==0||value.indexOf("+")==0)  len=len+1;		
		if(this.IntegerRex.test(value))
			return value.length<=len;
		return false;
}
LongTimeFormValidator.prototype.numberMinMax =function(value,min,max){		
		var ok=true;	
		if(typeof max=="string")
			ok=(value*1.0<=max);
		if(typeof min=="string")
			ok=ok&&(value*1.0>=min);
		return ok;
}
LongTimeFormValidator.prototype.limit =function(len,min, max){
		min = min || 0;
		max = max || Number.MAX_VALUE;
		return min <= len && len <= max;
	}
LongTimeFormValidator.prototype.LenB = function(str){
		return str.replace(/[^\x00-\xff]/g,"**").length;
	}
LongTimeFormValidator.prototype.ClearState =function(elem){		
			if(elem.style.color == "red")
				elem.style.color = "";
			var parent=elem.parentNode;
			var lastNode = parent.childNodes[parent.childNodes.length-1];				
			if(lastNode.id == "__ErrorMessagePanel"){
				parent.removeChild(lastNode);				
			}
		
}
LongTimeFormValidator.prototype.AddError =function(index, str){
		this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
		this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
	}
LongTimeFormValidator.prototype.Exec =function(op, reg){
		return new RegExp(reg,"g").test(op);
	}
LongTimeFormValidator.prototype.compare = function(op1,operator,op2){
		switch (operator) {
			case "ne":
				return (op1 != op2);
			case "gt":
				return (op1 > op2);
			case "ge":
				return (op1 >= op2);
			case "lt":
				return (op1 < op2);
			case "le":
				return (op1 <= op2);
			default:
				return (op1 == op2); 
		}
	}
LongTimeFormValidator.prototype.MustChecked =function(name, min, max){
		var groups = document.getElementsByName(name);
		var hasChecked = 0;
		min = min || 1;
		max = max || groups.length;
		for(var i=groups.length-1;i>=0;i--)
			if(groups[i].checked) hasChecked++;
		return min <= hasChecked && hasChecked <= max;
	}
	
LongTimeFormValidator.prototype.IsDate =function(dateval,formatString){
	
	if(typeof dateval== "undefined"||dateval.toString().length==0) return true;
    var arr = new Array();    
    if(dateval.indexOf("-") != -1){
        arr = dateval.toString().split("-");
    }else if(dateval.indexOf("/") != -1){
        arr = dateval.toString().split("/");
    }else{
        return false;
    }  
    switch(formatString){	    
    	case "dd-mm-yyyy" :
    		m = dateval.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
			if(m == null && dateval != "") return false;
		    if(arr[2].length==4){
		        var date = new Date(arr[2],arr[1]-1,arr[0]);
		        if(date.getFullYear()==arr[2] && date.getMonth()==arr[1]-1 && date.getDate()==arr[0]){
		            return true;
		        }
		    } 
		case "yyyy-mm-dd" :
		default:
			m = dateval.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
			if(m == null && dateval != "") return false;
		    if(arr[0].length==4){
		        var date = new Date(arr[0],arr[1]-1,arr[2]);
		        if(date.getFullYear()==arr[0] && date.getMonth()==arr[1]-1 && date.getDate()==arr[2]){
		            return true;
		        }
		    }
    }
    return false;
}
//验证格式为 2008-08-08 20:00:00
LongTimeFormValidator.prototype.IsLongDateTime =function (str, op) {	    
		var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;		
		var r = str.match(reg); 
		if(r == null && str != "")return false;		
		//var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
		var d;
		if(str != ""){
		  d= new Date(r[1], r[3]-1,r[4],r[5],r[6]);
		  return ((d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]));
		}
		return true;
    }
//验证格式如 2008-08-08 20:00	
LongTimeFormValidator.prototype.IsDateTime =function (str, op) {	    		
		var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/;  
		var r = str.match(reg); 
		if(r == null && str != "")return false;				
		var d;
		if(str != ""){
		  d= new Date(r[1], r[3]-1,r[4],r[5],r[6]);
		  return ((d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]));
		}
		return true;
    }
LongTimeFormValidator.prototype.validate=function(theForm,mode) {
		if(typeof theForm!='object'){   	 		
   			theForm=document.forms[0];
  		 }
	    this.first=false;	    
    	this.theForm=theForm;
    	this.mode=mode;
    	this.ElementIndex=0;
    	this.ErrorMessage.length = 1;
		this.ErrorItem.length = 1;		
		this.obj = theForm || event.srcElement;
		this.ErrorItem[0] = this.obj;			
		this.count = this.obj.elements.length;		
		this.viewstep=parseInt((this.count/100));
		
		var s=document.getElementsByTagName("select"); 
		for(var j=0;j<s.length;j++){s[j].style.visibility="hidden";} 
		var iWidth = document.documentElement.clientWidth; 
		var iHeight = document.documentElement.clientHeight; 
		var bgObj = document.createElement("div"); 
		bgObj.id="LongTimeFormValidatorBg";
		bgObj.style.cssText="position:absolute;left:-50px;top:-50px;width:0px;height:0px;filter:Alpha(Opacity=50);	opacity:0.7;background-color:#000000;z-index:101;"		
		bgObj.style.width=(1*iWidth+50)+"px";
		bgObj.style.height=(Math.max(document.body.clientHeight, iHeight)+50)+"px";		
		document.body.appendChild(bgObj);
	
    	var load=document.createElement("DIV");
		load.id="LongTimeFormValidator_loaddiv";
		//load.style.cssText="position:absolute;top:10px;width:500px;height:20px;border:1px #000 solid;display:block";
		load.style.cssText="position:absolute;top:"+(iHeight/2-50)+"px;left:"+(iWidth-300)/2+"px;z-index:102;display:block";
		
		var layer=document.createElement("layer");
		layer.name="waiting";
		layer.visibility="visible";
		layer.zIndex="20001"
		load.appendChild(layer);
		
		var table=document.createElement("table");
		table.border="2px";
		table.cellSpacing ="0px";
		table.cellPadding="0px";
		table.borderColorLight ="#FFFFFF";
		table.borderColorDark="#c3daf9";
		//table.bgColor="#E0E0E0";		
		var newRow = table.insertRow(0);
  		var newCell0 = newRow.insertCell(0); 
  		newCell0.id="LongTimeFormValidator_title";
  		newCell0.bgColor="#FFFFFF";
  		newCell0.height="30px";
  		newCell0.width="300px";
  		newCell0.align="center";
  		newCell0.innerHTML="<img class='img16' src='"+contextPath+"/webresource/images/loading2.gif'> <font color='#0080ff'>\u8BF7\u7A0D\u5019...</font>";//正在校验数据..
  		var newRow1 = table.insertRow(1);
  		var newCell1 = newRow1.insertCell(0); 
  		newCell1.bgColor ="#E0E0E0";
		newCell1.innerHTML="<div width='1px' height='5px' align='center' id='LongTimeFormValidator_loading' style='background-color:#6699cc'></div>";		
		layer.appendChild(table);		
		document.body.appendChild(load);		
		/**
		if(this.first==false){
			for(i=0;i<this.count;i++){
				this.ClearState(this.obj.elements[i]);
			}
		}
		*/
		//setTimeout("FormValidator_Validate()",1);			
		FormValidator_V_Cleari=0;
		FormValidator_ClearState();
		if (document.all) {
			document.onclick = donothing;
		}	
		
	}
function FormValidator_Validate(){
		try{			
			FormValidator_V.validateIt();
		}catch(e){}
}
function donothing(){
	return false;
}
function FormValidator_ClearState(){	
	while(FormValidator_V_Cleari<FormValidator_V.count){
		FormValidator_V.ClearState(FormValidator_V.obj.elements[FormValidator_V_Cleari]);
		FormValidator_V_Cleari++;		
		per=(FormValidator_V_Cleari)*100.0/FormValidator_V.count;
		if(FormValidator_V_Cleari%(2*FormValidator_V.viewstep)==0){					
			document.getElementById("LongTimeFormValidator_loading").style.width = per + "%";	
			document.getElementById("LongTimeFormValidator_loading").innerHTML = parseInt(per) + "%";		
			setTimeout("FormValidator_ClearState()",1);
			break;
		}		
	}
	if(FormValidator_V_Cleari>=FormValidator_V.count){
		document.getElementById("LongTimeFormValidator_loading").style.width = "1%";	
		document.getElementById("LongTimeFormValidator_title").innerHTML="<img class='img16' src='"+contextPath+"/webresource/images/loading2.gif'> <font color='#0080ff'>\u6B63\u5728\u6821\u9A8C\u6570\u636E...</font>";
		setTimeout("FormValidator_Validate()",1);	
	}
}